﻿using System;
using System.Linq;
using NHDay_Linq.Domain;
using NHibernate;
using NHibernate.Tool.hbm2ddl;
using NUnit.Framework;
using NHibernate.Linq;

namespace NHDay_Linq
{
	[TestFixture]
	public class T05_UnsupportedQueriesTests : TestBase
	{
		[TestFixtureSetUp]
		public void FixtureSetup()
		{
			CreateDatabase();
		}

		[Test]
		public void T01_InMemory_NestedQuery()
		{
			// use the in-memory objects

			// Create a list where each element is an anonymous type
			// that contains the person's first name and a collection of 
			// pets that are owned by them.
			var query = from person in People
						join pet in Pets on person equals pet.Owner into gj
						select new { OwnerName = person.FirstName, Pets = gj };

			foreach (var v in query)
			{
				// Output the owner's name.
				Console.WriteLine("{0}:", v.OwnerName);
				// Output each of the owner's pet's names.
				foreach (Pet pet in v.Pets)
					Console.WriteLine("  {0}", pet.Name);
			}
		}

		[Test]
		public void T02_NestedQuery()
		{
			// let's do the same but hitting the database now...
			using (ISession session = SessionFactory.OpenSession())
			using (ITransaction tx = session.BeginTransaction())
			{

				// perform the same query using ling to nhib
				var nhQuery = from person in session.Query<Person>()
							  join pet in session.Query<Pet>() on person equals pet.Owner into gj
				              select new {OwnerName = person.FirstName, Pets = gj};

				foreach (var v in nhQuery)
				{
					// Output the owner's name.
					Console.WriteLine("{0}:", v.OwnerName);
					// Output each of the owner's pet's names.
					foreach (Pet pet in v.Pets)
						Console.WriteLine("  {0}", pet.Name);
				}

				tx.Commit();
			}
		}

		[Test]
		public void T03_ProjectinWithJoin()
		{
			// let's do the same but hitting the database now...
			using (ISession session = SessionFactory.OpenSession())
			using (ITransaction tx = session.BeginTransaction())
			{

				// perform the same query using ling to nhib
				var nhQuery = from person in session.Query<Person>()
							  select new
							  {
								  OwnerName = person.FirstName,
								  Pets = person.Pets
							  }; 

				foreach (var v in nhQuery)
				{
					// Output the owner's name.
					Console.WriteLine("{0}:", v.OwnerName);
					// Output each of the owner's pet's names.
					foreach (Pet pet in v.Pets)
						Console.WriteLine("  {0}", pet.Name);
				}

				tx.Commit();
			}
		}
	}
}
